<template>
  <div class="self-service-payment">
    <van-nav-bar title="自助缴费" left-arrow @click-left="onBack" fixed>
      <template #right>
        <van-icon name="ellipsis" size="18" />
        <van-icon name="question-o" size="18" style="margin-left: 16px;" />
      </template>
    </van-nav-bar>

    <div class="content">
      <!-- 就诊人卡片 -->
      <div class="patient-card" @click="showPatientPicker">
        <div class="patient-info">
          <div class="patient-header">
            <h3 class="patient-name">{{ selectedPatient?.name || '请选择就诊人' }}</h3>
            <van-tag type="primary" size="medium" v-if="selectedPatient">{{selectedPatient?.relationship}}</van-tag>
          </div>
          <div class="patient-card-no" v-if="selectedPatient">
            {{ formatMedicalCard(selectedPatient.medicalCard) }}
          </div>
        </div>
        <div class="switch-patient">
          <span class="switch-text">切换就诊人</span>
          <van-icon name="arrow" />
        </div>
      </div>

      <!-- 卡内余额 -->
      <div class="balance-card">
        <div class="balance-label">卡内余额</div>
        <div class="balance-amount">¥{{ cardBalance.toFixed(2) }}</div>
      </div>

      <!-- 待缴费项目 -->
      <div class="payment-section">
        <h3 class="section-title">待缴费项目</h3>
        
        <!-- 动态待缴费项目列表（反填数据） -->
        <div v-if="paymentItems.length > 0" class="payment-list">
          <div 
            v-for="item in paymentItems" 
            :key="item.amountId"
            class="payment-item-card"
          >
            <div class="item-header">
              <h4 class="item-name">{{ item.expenseName || item.businessName || '门诊缴费' }}</h4>
              <div class="item-amount">¥{{ item.paymentAmount.toFixed(2) }}</div>
            </div>
            <div class="item-details">
              <div class="detail-row">
                <span class="detail-label">{{ item.departmentName }} {{ item.doctorName }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-time">{{ formatTime(item.operatingTime) }}</span>
              </div>
            </div>
            <div class="item-footer">
              <van-button 
                type="primary" 
                size="small" 
                round
                @click="handlePayment(item)"
              >
                去缴费
              </van-button>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <van-loading v-if="loadingPayments" type="spinner" size="40" vertical>
          加载中...
        </van-loading>

        <!-- 空状态：当没有加载且没有数据时显示 -->
        <van-empty 
          v-else-if="!loadingPayments && paymentItems.length === 0" 
          description="暂无待缴费项目"
          :image-size="100"
        />
        
      </div>
      
    </div>

    <!-- 就诊人选择器 -->
    <van-popup 
      v-model:show="showPicker" 
      position="bottom" 
      :round="true"
      :style="{ height: '60%' }"
    >
      <div class="picker-container">
        <div class="picker-header">
          <van-button 
            plain
            @click="showPicker = false"
            class="picker-cancel"
          >
            取消
          </van-button>
          <h3>选择就诊人</h3>
          <van-button 
            plain
            type="primary"
            @click="confirmPatient"
            class="picker-confirm"
          >
            确定
          </van-button>
        </div>
        
        <div class="patient-list">
          <div 
            v-for="patient in patients" 
            :key="patient.patientId"
            class="patient-option"
            :class="{ active: tempSelectedPatient?.patientId === patient.patientId }"
            @click="tempSelectedPatient = patient"
          >
            <div class="option-info">
              <div class="option-name">{{ patient.name }}</div>
              <div class="option-relation">{{ patient.relationship }}</div>
              <div class="option-card">{{ formatMedicalCard(patient.medicalCard) }}</div>
            </div>
            <van-icon 
              name="success" 
              color="#1989fa" 
              size="20"
              v-if="tempSelectedPatient?.patientId === patient.patientId"
            />
          </div>
          
          <van-empty 
            v-if="patients.length === 0" 
            description="暂无就诊人"
            :image-size="80"
          >
            <van-button 
              type="primary" 
              size="small"
              round
              @click="goToAddPatient"
            >
              添加就诊人
            </van-button>
          </van-empty>
        </div>
      </div>
    </van-popup>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item icon="contact" to="/profile">个人中心</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { api, type Patient } from '@/api'

const router = useRouter()
const activeTab = ref(0)

// 就诊人相关
const patients = ref<Patient[]>([])
const selectedPatient = ref<Patient | null>(null)
const tempSelectedPatient = ref<Patient | null>(null)
const showPicker = ref(false)

// 加载状态
const loadingPayments = ref(false)

// 卡内余额
const cardBalance = ref(0)

// 待缴费项目
interface PaymentItem {
  amountId: number | string
  operatingNum: string
  source: string
  paymentMethod: string
  paymentAmount: number
  paymentStatus: boolean
  balance: number
  operatingTime: string
  businessId: number | string
  businessName: string
  patientId: number | string
  name: string
  medicalCard: string
  expenseId: number | string
  expenseName: string | null
  appointmentId: number | string
  doctorName: string
  departmentId: number | string
  departmentName: string
}

const paymentItems = ref<PaymentItem[]>([])

// 返回
const onBack = () => {
  router.back()
}

// 格式化就诊卡号
const formatMedicalCard = (cardNo: string) => {
  if (!cardNo) return ''
  // 将卡号格式化为 622*********0909 的形式
  if (cardNo.length > 8) {
    const start = cardNo.substring(0, 3)
    const end = cardNo.substring(cardNo.length - 4)
    const middle = '*'.repeat(cardNo.length - 7)
    return `${start}${middle}${end}`
  }
  return cardNo
}

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  try {
    // 处理 ISO 格式时间：2025-10-16T15:23:31
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    // 如果时间格式不正确，返回原字符串
    return timeStr
  }
}

// 显示就诊人选择器
const showPatientPicker = () => {
  tempSelectedPatient.value = selectedPatient.value
  showPicker.value = true
}

// 确认选择就诊人
const confirmPatient = () => {
  if (tempSelectedPatient.value) {
    selectedPatient.value = tempSelectedPatient.value
    showPicker.value = false
    // 切换就诊人后重新加载待缴费项目
    loadPaymentItems()
  } else {
    Toast('请选择就诊人')
  }
}

// 跳转到添加就诊人页面
const goToAddPatient = () => {
  showPicker.value = false
  router.push('/patient/add')
}

// 加载就诊人列表
const loadPatients = async () => {
  try {
    const response = await api.getPatients()
    patients.value = response.data || []
    
    // 如果有就诊人且没有选中的，默认选中第一个
    if (patients.value.length > 0 && !selectedPatient.value) {
      selectedPatient.value = patients.value[0] || null
      loadPaymentItems()
    }
  } catch (error) {
    console.error('获取就诊人列表失败:', error)
    Toast('获取就诊人列表失败')
  }
}

// 根据就诊人ID加载待缴费项目（反填方法）
const loadPaymentItems = async () => {
  // 检查是否选择了就诊人
  if (!selectedPatient.value) {
    paymentItems.value = []
    cardBalance.value = 0
    return
  }

  // 开启加载状态
  loadingPayments.value = true
  
  try {
    // 获取当前选中的就诊人ID
    const patientId = selectedPatient.value.patientId
    
    console.log('开始获取待缴费项目，就诊人ID:', patientId)
    
    // 调用API获取待缴费项目
    const res = await api.getPaymentItems(patientId)
    
    console.log('待缴费项目API响应:', res)
    
    // 检查响应状态码和数据有效性
    if (res.code === 200) {
      // 清空原有待缴费项目数据
      paymentItems.value = []
      
      if (res.data && res.data.length > 0) {
        // 遍历返回的数据，逐条反填到待缴费项目列表
        for (let i = 0; i < res.data.length; i++) {
          const dataItem = res.data[i]
          
          // 构建待缴费项目对象（根据API返回的驼峰命名字段）
          const paymentItem: PaymentItem = {
            // 金额相关
            amountId: dataItem.amountId ?? '',
            paymentAmount: parseFloat(dataItem.paymentAmount || 0),
            balance: parseFloat(dataItem.balance || 0),
            
            // 费用类型
            expenseId: dataItem.expenseId || '',
            expenseName: dataItem.expenseName || null,
            
            // 科室和医生信息
            departmentId: dataItem.departmentId || '',
            departmentName: dataItem.departmentName || '',
            doctorName: dataItem.doctorName || '',
            
            // 时间信息
            operatingTime: dataItem.operatingTime || '',
            
            // 就诊人信息
            patientId: dataItem.patientId || patientId,
            name: dataItem.name || selectedPatient.value?.name || '',
            medicalCard: dataItem.medicalCard || selectedPatient.value?.medicalCard || '',
            
            // 其他信息
            operatingNum: dataItem.operatingNum || '',
            source: dataItem.source || '',
            paymentMethod: dataItem.paymentMethod || '',
            paymentStatus: dataItem.paymentStatus || false,
            businessId: dataItem.businessId || '',
            businessName: dataItem.businessName || '',
            appointmentId: dataItem.appointmentId || ''
          }
          
          // 添加到待缴费项目列表
          paymentItems.value.push(paymentItem)
        }
        
        // 更新卡内余额（从第一条数据获取）
        if (paymentItems.value.length > 0 && paymentItems.value[0] && paymentItems.value[0].balance) {
          cardBalance.value = paymentItems.value[0].balance
        }
        
        console.log(`成功反填 ${paymentItems.value.length} 条待缴费项目`)
        console.log('反填后的数据:', paymentItems.value)
      } else {
        // API返回成功但数据为空
        paymentItems.value = []
        cardBalance.value = 0
        console.log('API返回成功，但无待缴费项目数据')
      }
    } else {
      // 请求失败
      paymentItems.value = []
      cardBalance.value = 0
      
      console.log('API请求失败，响应码:', res.code)
      
      // 显示错误提示
      Toast(res.message || '获取待缴费项目失败')
    }
  } catch (error) {
    // 捕获异常
    console.error('获取待缴费项目异常:', error)
    Toast('获取待缴费项目失败，请稍后重试')
    
    // 清空数据
    paymentItems.value = []
    cardBalance.value = 0
  } finally {
    // 关闭加载状态
    loadingPayments.value = false
  }
}

// 处理缴费
const handlePayment = (item: PaymentItem) => {
  // 验证必要的数据
  if (!item.amountId || item.amountId === '' || item.amountId === 0) {
    Toast.fail('缴费项目信息不完整，无法支付')
    console.error('AmountId无效:', item.amountId, '完整数据:', item)
    return
  }

  console.log('跳转到支付页面，传递数据:', item)
  
  // 跳转到支付页面，传递所有反填的缴费项目信息
  router.push({
    path: '/zhifubao/zhifu',
    query: {
      // 基础信息
      amountId: item.amountId.toString(),
      operatingNum: item.operatingNum,
      source: item.source,
      paymentMethod: item.paymentMethod,
      paymentStatus: item.paymentStatus.toString(),
      
      // 金额信息
      paymentAmount: item.paymentAmount.toString(),
      balance: item.balance.toString(),
      
      // 费用类型
      expenseId: item.expenseId.toString(),
      expenseName: item.expenseName || '',
      
      // 科室和医生信息
      departmentId: item.departmentId.toString(),
      departmentName: item.departmentName,
      doctorName: item.doctorName,
      
      // 时间信息
      operatingTime: item.operatingTime,
      
      // 就诊人信息
      patientId: item.patientId.toString(),
      name: item.name,
      medicalCard: item.medicalCard,
      
      // 其他信息
      businessId: item.businessId.toString(),
      businessName: item.businessName,
      appointmentId: item.appointmentId.toString()
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  loadPatients()
})
</script>

<style scoped>
.self-service-payment {
  min-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.content {
  width: 100%;
  max-width: 480px; /* 适配主流移动端宽度，避免过宽 */
  margin: 0 auto;
  padding-top: calc(46px + env(safe-area-inset-top, 0px)); /* 顶部导航栏+安全区 */
  padding-left: 16px;
  padding-right: 16px;
  padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px)); /* 预留底部tabbar与安全区 */
  box-sizing: border-box;
}

/* 就诊人卡片 */
.patient-card {
  background: linear-gradient(135deg, #e8f4ff 0%, #f0f9ff 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.1);
}

.patient-info {
  flex: 1;
}

.patient-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.patient-name {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin: 0;
}

.patient-card-no {
  font-size: 14px;
  color: #646566;
  letter-spacing: 1px;
}

.switch-patient {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1989fa;
  font-size: 14px;
}

.switch-text {
  white-space: nowrap;
}

/* 卡内余额 */
.balance-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.balance-label {
  font-size: 14px;
  color: #969799;
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 32px;
  font-weight: 600;
  color: #323233;
}

/* 待缴费项目 */
.payment-section {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 0 0 12px 0;
}

.payment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-item-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-name {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 0;
}

.item-amount {
  font-size: 18px;
  font-weight: 600;
  color: #ee0a24;
}

.item-details {
  margin-bottom: 12px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.detail-label {
  font-size: 13px;
  color: #646566;
}

.detail-time {
  font-size: 12px;
  color: #969799;
}

.item-footer {
  display: flex;
  justify-content: flex-end;
}

.item-footer .van-button {
  min-width: 80px;
}

/* 就诊人选择器 */
.picker-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.picker-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 0;
}

.picker-cancel,
.picker-confirm {
  font-size: 14px;
}

.patient-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.patient-option {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.patient-option:active {
  transform: scale(0.98);
}

.patient-option.active {
  border-color: #1989fa;
  background: linear-gradient(135deg, #e8f4ff 0%, #f0f9ff 100%);
}

.option-info {
  flex: 1;
}

.option-name {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 6px;
}

.option-relation {
  font-size: 13px;
  color: #646566;
  margin-bottom: 4px;
}

.option-card {
  font-size: 12px;
  color: #969799;
  letter-spacing: 1px;
}

/* 加载状态 */
:deep(.van-loading) {
  padding: 40px 20px;
  text-align: center;
}

/* 空状态 */
:deep(.van-empty) {
  padding: 40px 20px;
}


/* 中等屏幕（小平板）适配，稍微放宽最大宽度 */
@media (min-width: 480px) and (max-width: 768px) {
  .content {
    max-width: 520px;
  }
}
</style>

